<template>
  <div>
    <el-row :gutter="20">
      <!-- 楼栋楼层 -->
      <el-col :span="6">
        <el-form :inline="true" :model="dataForm" @keyup.enter.native="floorAdd(0)">
          <el-form-item v-if="isAuth('hotel:thotelfloor:save')">
            <el-input v-model="dataForm.name" placeholder="整栋名" clearable></el-input>
          </el-form-item>
          <el-form-item>
            <el-button v-if="isAuth('hotel:thotelfloor:save')" @click="floorAdd(0)">添加</el-button>
          </el-form-item>
        </el-form>
        <el-tree :data="floorDataList" node-key="id" default-expand-all :expand-on-click-node="false" :node-click="view">
          <span class="custom-tree-node" slot-scope="{ node, data }">
            <span>
              <el-button @click="thotelfloorroomClick(data)" :style="data.parentId == 0 ? 'font-weight: bold;' : ''" type="text" size="mini" >{{ node.label }}</el-button>
            </span>
            <span>
              <el-button type="text" v-if="data.parentId == 0" size="mini" @click="() => append(data)">添加楼层</el-button>
              <el-button type="text" size="mini" @click="() => edit(data)">编辑</el-button>
              <el-button type="text" size="mini" @click="() => remove(node, data)">删除</el-button>
            </span>
          </span>
        </el-tree>
      </el-col>
      <!-- 房间 -->
      <el-col :span="18">
        <el-form :inline="true" :model="dataForm" @keyup.enter.native="getDataList()">
          <!-- <el-form-item><el-input v-model="dataForm.key" placeholder="参数名" clearable></el-input></el-form-item> -->
          <el-form-item>
            <span>【{{currName?currName:'全部'}}】房间属性</span>
            <!-- <el-button @click="getDataList()">{{ $t('Common.Query') }}</el-button> -->
            <el-button v-if="isAuth('hotel:thotelfloorroom:save')" type="primary" @click="addOrUpdateHandle('',1)">新增房间</el-button>
            <el-button v-if="isAuth('hotel:thotelfloorroom:save')" type="primary" @click="addOrUpdateHandle('',2)">批量新增</el-button>
            <el-button v-if="isAuth('hotel:thotelfloorroom:delete')" type="danger" @click="deleteHandle()" :disabled="dataListSelections.length <= 0">{{ $t('Common.BulkDelete') }}</el-button>
          <el-button v-if="isAuth('hotel:thotelfloorroom:delete')" type="danger" @click="deletecount()" >全部删除</el-button>

          </el-form-item>

          <el-form-item style="float: right;" label="" v-if="isAuth('hotel:hotelseller:list')">
            <el-select
              multiple
              collapse-tags
              clearable
              style="width:180px;"
              v-model="sellerIds"
              filterable
              remote
              reserve-keyword
              @change="selectSeller"
              placeholder="商家名称"
              :remote-method="remoteMethod"
              :loading="loading"
            >
              <el-option v-for="item in platformSeller" :key="item.id" :label="item.name" :value="item.id"></el-option>
            </el-select>
          </el-form-item>

        </el-form>
        <el-table :data="dataList" border v-loading="dataListLoading" @selection-change="selectionChangeHandle" style="width: 100%;">
          <el-table-column type="selection" header-align="center" align="center" width="50"></el-table-column>
          <el-table-column prop="sellerName" header-align="center" align="center" label="商家"></el-table-column>
          <el-table-column prop="fpname" header-align="center" align="center" label="整栋"></el-table-column>
          <el-table-column prop="fname" header-align="center" align="center" label="楼层"></el-table-column>
          <el-table-column prop="roomName" header-align="center" align="center" label="房型"></el-table-column>
          <el-table-column prop="roomSignNum" header-align="center" align="center" label="房号">
         <!--   <template slot-scope="scope">
              <span>{{ scope.row.roomSign }}{{ scope.row.roomNum }}</span>
            </template> -->
          </el-table-column>
          <el-table-column prop="roomDesc" header-align="center" align="center" label="房间描述">
            <template slot-scope="scope">
                <el-tooltip class="item" effect="dark" :content="scope.row.roomDesc" placement="right-start">
                    <span>{{ scope.row.roomDesc}}</span>
                 </el-tooltip>

            </template>
          </el-table-column>
          <el-table-column prop="createTime" header-align="center" align="center" label="创建时间" width="160"></el-table-column>
          <el-table-column fixed="right" header-align="center" align="center" width="150" label="操作">
            <template slot-scope="scope">
              <el-button type="text" size="small" @click="addOrUpdateHandle(scope.row.id,1)">修改</el-button>
              <el-button type="text" size="small" @click="deleteHandle(scope.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          @size-change="sizeChangeHandle"
          @current-change="currentChangeHandle"
          :current-page="pageIndex"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageSize"
          :total="totalPage"
          layout="total, sizes, prev, pager, next, jumper"
        ></el-pagination>
        <!-- 弹窗, 新增 / 修改 -->
        <add-or-update v-if="addOrUpdateVisible" ref="addOrUpdate" @refreshDataList="getDataList"></add-or-update>
        <floorAddOrUpdate v-if="floorAddOrUpdateVisible" ref="floorAddOrUpdate" @refreshDataList="getFloorList"></floorAddOrUpdate>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import AddOrUpdate from './thotelfloorroom-add-or-update';
import floorAddOrUpdate from './thotelfloor-add-or-update';
export default {
  data() {
    return {
      loading: false,
      sellerIds: [],
      currName:'',
      roomList: [],
      floorDataList: [],
      dataForm: {
        key: '',
        name:'',
        floorId:'',
      },
      dataList: [],
      pageIndex: 1,
      pageSize: 10,
      totalPage: 0,
      dataListLoading: false,
      dataListSelections: [],
      platformSeller:[],
      addOrUpdateVisible: false,
      floorAddOrUpdateVisible: false
    };
  },
  components: {
    AddOrUpdate,floorAddOrUpdate
  },
  activated() {
    this.getDataList();
    this.getFloorList();
    this.remoteMethod();
  },
  methods: {
    thotelfloorroomClick(data){
      this.pageIndex = 1
      this.currName = data.label
      this.dataForm.floorId = data.id
      this.getDataList();
    },
    selectSeller(id, value) {
      this.getDataList();
      this.getFloorList();
    },
    //加载平台商家数据
    remoteMethod(query) {
      if(this.isAuth('hotel:hotelseller:list')){
        this.loading = true;
        this.$http({
          url: this.$http.adornUrl("/hotel/hotelseller/platformSeller"),
          method: "get",
          params: this.$http.adornParams({
            sellerName: query
          })
        }).then(({ data }) => {
          this.loading = false;
          if (data && data.code === 0) {
            this.platformSeller = data.page.list;
          } else {
            this.$message.error(data.msg);
          }
        });
      }
    },
    // 获取数据列表
    getDataList() {
      this.dataListLoading = true;
      var ids = '';
      if (this.sellerIds) {
        this.sellerIds.forEach((item, index) => {
          ids += item + ',';
        });
        ids = ids.substring(0, ids.length - 1);
      }
      this.$http({
        url: this.$http.adornUrl('/hotel/thotelfloorroom/list'),
        method: 'get',
        params: this.$http.adornParams({
          page: this.pageIndex,
          limit: this.pageSize,
          floorId: this.dataForm.floorId,
          ids: ids
        })
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.dataList = data.page.records;
          this.totalPage = data.page.total;
        } else {
          this.dataList = [];
          this.totalPage = 0;
        }
        this.dataListLoading = false;
      });
    },
    // 每页数
    sizeChangeHandle(val) {
      this.pageSize = val;
      this.pageIndex = 1;
      this.getDataList();
    },
    // 当前页
    currentChangeHandle(val) {
      this.pageIndex = val;
      this.getDataList();
    },
    // 多选
    selectionChangeHandle(val) {
      this.dataListSelections = val;
    },
    // 新增 / 修改
    addOrUpdateHandle(id,type) {
      this.addOrUpdateVisible = true;
      this.$nextTick(() => {
        this.$refs.addOrUpdate.init(id,type);
      });
    },
    // 新增 / 修改
    floorAddOrUpdateHandle(id) {
      this.floorAddOrUpdateVisible = true;
      this.$nextTick(() => {
        this.$refs.floorAddOrUpdate.init(id);
      });
    },
    deletecount(){
      this.$confirm(`确定要执行全部删除操作?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http({
          url: this.$http.adornUrl('/hotel/thotelfloorroom/deletecount'),
          method: 'post',
        }).then(({ data }) => {
           if (data && data.code === 0) {
              if(data.i==0){
                this.$message({
                  message: this.$t('Common.OperationSuccessful'),
                  type: 'success',
                  duration: 1500,
                  onClose: () => {
                    this.getDataList();
                  }
                });
              }else{
                this.$message.error("部分房间正在被使用,不能删除");
                this.getDataList();
              }
          } else {
            this.$message.error(data.msg);
          }
        });
      });
    },
    // 删除
    deleteHandle(id) {
      var ids = id
        ? [id]
        : this.dataListSelections.map(item => {
            return item.id;
          });
      this.$confirm(`确定对[id=${ids.join(',')}]进行[${id ? '删除' : '批量删除'}]操作?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http({
          url: this.$http.adornUrl('/hotel/thotelfloorroom/delete'),
          method: 'post',
          data: this.$http.adornData(ids, false)
        }).then(({ data }) => {
          if (data && data.code === 0) {
            if(data.i==0){
              this.$message({
                message: this.$t('Common.OperationSuccessful'),
                type: 'success',
                duration: 1500,
                onClose: () => {
                  this.getDataList();
                }
              });
            }else{
              this.$message.error("以下"+i+"间房正在被使用,不能删除");
            }

          } else {
            this.$message.error(data.msg);
          }
        });
      });
    },
    //获取楼层楼栋数据
    getFloorList() {
      var ids = '';
      if (this.sellerIds) {
        this.sellerIds.forEach((item, index) => {
          ids += item + ',';
        });
        ids = ids.substring(0, ids.length - 1);
      }
      this.$http({
        url: this.$http.adornUrl('/hotel/thotelfloor/data'),
        method: 'get',
        params: this.$http.adornParams({
          ids: ids
        })
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.floorDataList = data.data;
        } else {
          this.floorDataList = [];
        }
      });
    },
    view(data,node,mode){
      this.dataForm.floorId = data.id
      this.currName = data.label
      this.getDataList();
    },
    edit(data){
      var name = data.parentId == 0 ? '整栋' : '楼层'
      this.$prompt('', '编辑'+name+'名称', {
        inputValue:data.label,
        closeOnClickModal:false,
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern: /^[\s\S]*.*[^\s][\s\S]*$/,
        inputErrorMessage: name+'名称不能为空'
      })
      .then(({ value }) => {
        this.$http({
          url: this.$http.adornUrl(`/hotel/thotelfloor/update`),
          method: 'post',
          data: this.$http.adornData({
            id:data.id,
            name:value
          })
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.$message({
              message: this.$t('Common.OperationSuccessful'),
              type: 'success',
              duration: 1500,
            })
            this.getFloorList()
          } else {
            this.$message.error(data.msg)
          }
        })
      })
    },
    append(data) {
      this.$prompt('', '添加楼层', {
        closeOnClickModal:false,
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern: /^[\s\S]*.*[^\s][\s\S]*$/,
        inputErrorMessage: '楼层不能为空'
      })
      .then(({ value }) => {
        this.$http({
          url: this.$http.adornUrl(`/hotel/thotelfloor/save`),
          method: 'post',
          data: this.$http.adornData({
            'parentId': data.id,
            'name': value,
          })
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.$message({
              message: this.$t('Common.OperationSuccessful'),
              type: 'success',
              duration: 1500,
            })
            this.getFloorList()
          } else {
            this.$message.error(data.msg)
          }
        })
      })
    },
    remove(node, data) {
      this.$confirm(`确定对 [${data.parentId == 0 ? '整栋' : '楼层'}] ${data.label}进行删除操作?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http({
          url: this.$http.adornUrl('/hotel/thotelfloor/delete'),
          method: 'post',
          data: this.$http.adornData([data.id], false)
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.$message({
              message: this.$t('Common.OperationSuccessful'),
              type: 'success',
              duration: 1500
            })
            const parent = node.parent;
            const children = parent.data.children || parent.data;
            const index = children.findIndex(d => d.id === data.id);
            children.splice(index, 1);
          } else {
            this.$message.error(data.msg)
          }
        })
      })
    },
    floorAdd(parentId){
      var name = this.dataForm.name
      if(!name){
        this.$message.error("整栋名称不可为空")
        return false
      }
      this.$http({
        url: this.$http.adornUrl(`/hotel/thotelfloor/save`),
        method: 'post',
        data: this.$http.adornData({
          'parentId': parentId,
          'name': this.dataForm.name,
        })
      }).then(({data}) => {
        if (data && data.code === 0) {
          this.$message({
            message: this.$t('Common.OperationSuccessful'),
            type: 'success',
            duration: 1500,
          })
          this.dataForm.name = ""
          this.getFloorList()
        } else {
          this.$message.error(data.msg)
        }
      })
    },
  }
};
</script>

<style>
  .custom-tree-node {
      flex: 1;
      display: flex;
      align-items: center;
      justify-content: space-between;
      font-size: 14px;
      padding-right: 8px;
    }
</style>
